<template>
  <div class="flex justify-center min-h-screen p-4 font-sans bg-[#e9f3ff]">
    <div
      class="relative z-10 w-full max-w-md p-8 bg-white shadow-md login-card rounded-[20px] border border-[#e2e8f0] mt-[100px]"
    >
      <div class="mb-[40px] login-header flex flex-col items-center">
        <div
          class="flex items-center justify-center w-[64px] h-[64px] mx-auto mb-4 transition-transform duration-300 logo bg-gradient-to-r from-[#06b6d4] to-[#6366f1] rounded-[20px] hover:scale-110"
        >
          <span class="text-[28px] font-bold text-white">AI</span>
        </div>
        <h2 class="text-[20px] font-semibold text-[#1e293b]">
          客户服务管理平台
        </h2>
        <p class="mt-1 text-sm text-[#64748b]">高效匹配，智能赋能</p>
      </div>

      <a-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="flex flex-col items-center justify-center gap-[20px]"
      >
        <a-form-item
          name="phone"
          class="mb-[20px] form-item flex justify-center"
        >
          <a-input
            v-model:value="loginForm.phone"
            type="tel"
            placeholder="请输入手机号"
            :disabled="isLoading || isCounting"
            maxlength="11"
            class="w-[500px] h-[50px] transition-all duration-200 rounded-[10px] border-[#cbd5e1] focus:border-[#06b6d4] focus:ring-1 focus:ring-[#06b6d4]"
          >
          </a-input>
        </a-form-item>

        <a-form-item
          name="code"
          class="mb-[24px] form-item flex justify-center"
        >
          <div class="flex gap-3">
            <a-input
              v-model:value="loginForm.code"
              type="text"
              placeholder="请输入6位验证码"
              :disabled="isLoading || isCounting"
              maxlength="6"
              class="w-[350px] flex-1 transition-all duration-200 rounded-[10px] border-[#cbd5e1] focus:border-[#06b6d4] focus:ring-1 focus:ring-[#06b6d4]"
            >
            </a-input>

            <a-button
              :disabled="isLoading || isCounting || !loginForm.phone"
              @click="sendCode"
              :class="[
                'w-[140px] h-[48px] rounded-[10px] text-sm font-medium transition-all duration-200 ml-[10px]',
                isCounting || isLoading || !loginForm.phone
                  ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                  : 'bg-[#5765e2] text-white hover:bg-[#4a54d4]',
              ]"
            >
              {{ isCounting ? `${countDown}s重发` : "获取验证码" }}
            </a-button>
          </div>
        </a-form-item>

        <a-button
          @click="handleLogin"
          :loading="isLoading"
          class="w-full max-w-[500px] h-[48px] text-base font-medium text-white transition-all duration-300 rounded-[24px] shadow-sm bg-gradient-to-r from-[#06b6d4] to-[#6366f1] hover:from-[#0596b4] hover:to-[#5b5fe7] hover:shadow-md"
        >
          立即登录
        </a-button>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { sendMsg, loginApi } from "@/api/index.js";

const router = useRouter();
const loginFormRef = ref(null);
const loginForm = reactive({
  phone: "",
  code: "",
});

const rememberMe = ref(false);
const isLoading = ref(false);
const isCounting = ref(false);
const countDown = ref(60);
let countDownTimer = null;

// 页面销毁时清理定时器
onUnmounted(() => {
  if (countDownTimer) {
    clearInterval(countDownTimer);
  }
});

const loginRules = reactive({
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      type: "string",
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号（11位数字）",
      trigger: ["blur", "change"],
    },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 6, max: 6, message: "验证码长度为6位", trigger: "blur" },
    { pattern: /^\d{6}$/, message: "验证码仅支持数字", trigger: "blur" },
  ],
});

const isPhoneValid = (phone) => {
  const phoneStr = String(phone).trim();
  const phoneReg = /^1[3-9]\d{9}$/;
  return phoneReg.test(phoneStr);
};

const sendCode = async () => {
  if (!isPhoneValid(loginForm.phone)) {
    message.warning("请输入正确的手机号");
    return;
  }

  try {
    // 先显示加载状态
    isLoading.value = true;
    const res = await sendMsg({ phone: String(loginForm.phone) });

    if (res.code === 200) {
      message.success("验证码已发送至您的手机");
      // 只有成功才开始倒计时
      isCounting.value = true;
      countDown.value = 60;

      countDownTimer = setInterval(() => {
        countDown.value--;
        if (countDown.value <= 0) {
          clearInterval(countDownTimer);
          isCounting.value = false;
        }
      }, 1000);
    } else {
      message.error(res.msg || "发送验证码失败，请稍后重试");
    }
  } catch (error) {
    console.log("接口调用失败：", error);
    message.error("网络异常，发送验证码失败");
  } finally {
    // 无论成功失败都关闭加载状态
    isLoading.value = false;
  }
};

const handleLogin = async () => {
  try {
    await loginFormRef.value.validateFields();
  } catch (error) {
    return;
  }

  isLoading.value = true;
  try {
    const res = await loginApi({
      phone: String(loginForm.phone),
      code: String(loginForm.code),
    });

    if (res.code === 200) {
      message.success("登录成功，正在跳转...");
      localStorage.setItem("token", res.data.token);
      router.push("/user");
    } else {
      message.error(res.msg || "登录失败，请检查验证码");
    }
  } catch (error) {
    console.log("登录接口失败：", error);
    message.error("网络异常，登录失败");
  } finally {
    isLoading.value = false;
  }
};
</script>
